//
//  HomePageViewController.m
//  CivilianTravel
//
//  Created by xalo on 16/7/12.
//  Copyright © 2016年 许仕杰. All rights reserved.
//

#import "HomePageViewController.h"
#import "CityView.h"
#import "XSJScrollView.h"
#import "TourViewController.h"
#import "HomePageModel.h"
#import "CityModel.h"
#import "SpotModel.h"
#import "LoginViewController.h"
#import "ImageCollectionViewCell.h"
#import "CircleCollectionViewLayout.h"
#import "ShoppingViewController.h"
#import "InformationViewController.h"
#import "HomePageTableViewCell.h"
#import "PassValue.h"

#define KRatioW   self.view.frame.size.width / 414
#define KRatioH   self.view.frame.size.height / 736
@interface HomePageViewController ()<UIPickerViewDelegate,UIPickerViewDataSource,UICollectionViewDataSource,UICollectionViewDelegate,UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource,AMapLocationManagerDelegate>
//搜索框
@property (nonatomic, strong)UISearchBar *search;

//存放搜索结果的数组
@property(nonatomic,strong)NSMutableArray *resultArray;

@property(nonatomic, strong)UITableView *tableView;

@property (nonatomic, strong)CityView *city;

@property (nonatomic, assign)NSInteger provinceCount;
//动态图
@property (nonatomic, strong)UIImageView *trendsImage;

//背景图
@property (nonatomic, strong)UIImageView *homeImage;

//省份模型
@property (nonatomic, strong)NSMutableArray *provinceArray;
//第一个pickView城市数组
@property (nonatomic, strong)NSArray *allCity;
//城市模型
@property (nonatomic, strong)NSMutableArray *cityArray;
//第二个pickViw选中的城市
@property (nonatomic, strong)NSArray *seleCity;
//景点
@property (nonatomic, strong)NSMutableArray *spotArray;

@property (nonatomic, strong)UICollectionView *currentCollection;

//毛玻璃相框
@property (nonatomic, strong)UIImageView *visualImage;

//毛玻璃
@property (nonatomic, strong)UIVisualEffectView *visual;
//存放城市
@property (nonatomic, strong)NSMutableDictionary *specificDic;

/** 地理位置 */
@property (nonatomic, strong) UILabel *location;

/** 存放缓存图片 */
@property (nonatomic, copy) NSArray *images;

/** 地图 */
@property (nonatomic, strong) AMapLocationManager *locationManager;

/** 点击事件切换视图 */
@property (nonatomic, assign) NSInteger selectTrue;

/** 选择城市的ID */
@property (nonatomic, strong) NSString *cityID;

/** 省份的ID */
@property (nonatomic, strong) NSString *specificID;

/** 加载开始 */
@property (nonatomic, assign) NSInteger start;

@end

@implementation HomePageViewController

- (UILabel *)location{
    if (!_location) {
        _location = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kWidth/10 * KRatioW, 35 * KRatioH)];
    }
    return _location;
}

- (UICollectionView *)currentCollection{
    if (!_currentCollection) {
            CircleCollectionViewLayout *layou = [[CircleCollectionViewLayout alloc] init];
            self.currentCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 48*KRatioW, kWidth, kHeight) collectionViewLayout:layou];
        _currentCollection.backgroundColor = [UIColor clearColor];
        _currentCollection.dataSource = self;
        _currentCollection.delegate = self;
    }
    return _currentCollection;
}

//创建tableview
- (UITableView *)tableView{
    if(!_tableView){
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(self.view.frame.origin.x, 64, self.view.frame.size.width,kHeight)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.rowHeight = 44;
    _tableView.layer.cornerRadius = 5;
    _tableView.tableFooterView = [[UIView alloc]init];
    }
    return _tableView;
}

-(NSMutableArray *)resultArray{
    
    if (!_resultArray) {
        _resultArray = [NSMutableArray array];
    }
    return _resultArray;
}

- (UIImageView *)trendsImage{
    if (!_trendsImage) {
        _trendsImage = [[UIImageView alloc] initWithFrame:CGRectMake(1/2.0*kWidth-1/6.0*kWidth*KRatioW, 1/2.0*kHeight-1/6.0*kWidth*KRatioW, 1/3.0*kWidth*KRatioW, 1/3.0*kWidth*KRatioW)];
        _trendsImage.image = [UIImage imageNamed:@"trends"];
        _trendsImage.layer.cornerRadius = 1/6.0*kWidth*KRatioW;
        _trendsImage.layer.masksToBounds = YES;
        _trendsImage.userInteractionEnabled = YES;
    }
    return _trendsImage;
}

- (UIImageView *)homeImage{
    if (!_homeImage) {
        _homeImage = [[UIImageView alloc] initWithFrame:self.view.frame];
    }
    return _homeImage;
}

- (NSMutableDictionary *)specificDic{
    if (!_specificDic) {
        _specificDic = [NSMutableDictionary dictionary];
    }
    return _specificDic;
}

-(NSArray *)allCity{
    if (!_allCity) {
        _allCity = [NSArray array];
    }
    return _allCity;
}


- (NSArray *)seleCity{
    if (!_seleCity) {
        _seleCity = [NSArray array];
    }
    return _seleCity;
}



- (NSMutableArray *)provinceArray{
    if (!_provinceArray) {
        _provinceArray = [NSMutableArray array];
    }
    return _provinceArray;
}


//UISearchBar作为tableview的头部
- (UISearchBar *)search{
    if (!_search) {
        _search = [[UISearchBar alloc] initWithFrame:CGRectMake(kWidth/5, 0, kWidth/5*3, 35)];
        _search.delegate = self;
        _search.keyboardType = UIKeyboardAppearanceDefault;
        _search.placeholder = @"请输入搜索关键字";
        _search.barTintColor = [UIColor grayColor];
        _search.searchBarStyle = UISearchBarStyleDefault;
        _search.barStyle = UIBarStyleDefault;
    }
    return _search;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.selectTrue = 1;
    self.provinceCount = 0;
    if (!self.location.text) {
        
        self.location.text = @"西安市";
    }
    [self.tableView registerNib:[UINib nibWithNibName:@"HomePageTableViewCell" bundle:nil] forCellReuseIdentifier:@"table_cell"];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    //设置背景图
    self.homeImage.image = [UIImage imageNamed:@"back.jpg"];
    [self.view addSubview:self.homeImage];
    //注册
    [self.currentCollection registerNib:[UINib nibWithNibName:@"ImageCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"Cell"];
//    [self.view addSubview:self.currentCollection];
    //设置导航栏按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:self.location.text style:UIBarButtonItemStylePlain target:self action:@selector(cityAction)];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithimage:@"login" selectImage:@"loginSelect" title:nil target:self action:@selector(loginAction)];
    //添加搜索框
    self.navigationItem.titleView = self.search;
    //请求数据
    [self requestProvinceDataSource];
    [self.view addSubview:self.currentCollection];
    [self.view addSubview:self.trendsImage];
    
    //添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture)];
    
    [self.trendsImage addGestureRecognizer:tap];
    //地图定位
    self.locationManager = [[AMapLocationManager alloc] init];
    self.locationManager.delegate = self;
    [self.locationManager startUpdatingLocation];
    //上拉加载数据
    //添加下拉刷新
    self.tableView.mj_header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
        //刷新之前清空数组
        [self.spotArray removeAllObjects];
        [self loadTableViewDataSourceWithCityID:self.cityID start:0 limit:20];
        
    }];
    //添加上拉加载
    self.tableView.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
        self.start += 20;
        [self loadTableViewDataSourceWithCityID:self.cityID start:self.start limit:20];
    }];

}

#pragma mark -- 手势的实现方法
- (void)tapGesture{
    if (!self.cityID) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"没有网络，请检查网络" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alert show];
    } else {
    InformationViewController *information = [[InformationViewController alloc] init];
    if ([self.cityID isEqualToString:@"37"]) {
        self.cityID = @"1";
    } else if ([self.cityID isEqualToString:@"518"]||[self.cityID isEqualToString:@"520"]||[self.cityID isEqualToString:@"527"]||[self.cityID isEqualToString:@"528"]||[self.cityID isEqualToString:@"530"]||[self.cityID isEqualToString:@"531"]){
        self.cityID = @"33";
    }
    information.cityID = self.cityID;
    [self.navigationController pushViewController:information animated:YES];
    }
}

#pragma mark -- 数据请求
//请求数据省份
- (void)requestProvinceDataSource{
    [RequestManager fetchDataWithUrl:@"http://www.roadqu.com/api/mobile/qunawan/city/provincelist" parameter:@{@"a_t":@"1468409445000",@"token":@"578624ce19a3f",@"sign":@"4b453e0843c2b7d0ba1023b77b7aeb6bbd5058bf"} method:@"POST" compeleted:^(NSData *data) {
        NSDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSMutableSet *set = bigDic[@"data"];
        for (NSDictionary *smallDic in set) {
            NSSet *districtSet = smallDic[@"provincelist"];
            for (NSDictionary *districtDIC in districtSet) {
                self.provinceCount++;
                HomePageModel *model = [[HomePageModel alloc] init];
                [model setValuesForKeysWithDictionary:districtDIC];
                [self requestCityDataSource:model.ID.integerValue province:model.name];
                [self.provinceArray addObject:model];
            }
        }
    } updateUI:^{
    }];
}

//请求数据源
- (void)requestCityDataSource:(NSInteger)integer province:(NSString *)province{

    [RequestManager fetchDataWithUrl:@"http://www.roadqu.com/api/mobile/qunawan/city/list" parameter:@{@"pid":@(integer),@"token":@"578624ce19a3f"} method:@"POST" compeleted:^(NSData *data) {
        NSDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
#warning 没有网络时容易移除错误
        if ([bigDic[@"count"] isEqual: @(0)]) {
            CityModel *model = [[CityModel alloc] init];
            model.name = province;
            model.ID = @(integer);
            self.cityArray = [NSMutableArray array];
            [self.cityArray addObject:model];
//            NSLog(@"_____________%@",province);
        } else {
            NSMutableSet *dataSet = bigDic[@"data"];
            self.cityArray = [NSMutableArray array];
            for (NSDictionary *smallDic in dataSet) {
//            NSLog(@"**********%@",smallDic);
                CityModel *model = [[CityModel alloc] init];
                [model setValuesForKeysWithDictionary:smallDic];
                [self.cityArray addObject:model];
            }
        }
        //给字典赋值，使得省份与城市对应
        [self.specificDic setValue:self.cityArray forKey:province];

    } updateUI:^{
        if (self.provinceCount == self.specificDic.allKeys.count) {
            for (NSString *string in self.specificDic) {
                NSMutableArray *array = self.specificDic[string];
                for (CityModel *model in array) {
                    if ([self.location.text isEqualToString:model.name]) {
                        self.cityID = model.ID.description;
                        [self requestSpotWithCityId:model.ID];
                        break;
                    }
                }
            }
        }


    }];
}

//城市请求
-(void)requestSpotWithCityId:(NSNumber *)cityId{
    [RequestManager fetchDataWithUrl:@"http://www.roadqu.com/api/mobile/qunawan/poi/search" parameter:@{@"a_t":@"1468410964000",@"radius":@0,@"eachpage":@20,@"startpos":@0,@"cityid":cityId,@"token":@"578624ce19a3f"} method:@"POST" compeleted:^(NSData *data) {
        self.spotArray = [NSMutableArray array];
        NSDictionary *BigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        for (NSDictionary *dic in BigDic[@"data"]) {
            SpotModel *desModol = [[SpotModel alloc]init];
            [desModol setValuesForKeysWithDictionary:dic];
            [self.spotArray addObject:desModol];
        }
        
    } updateUI:^{
        NSMutableArray *array = [NSMutableArray array];
        for (SpotModel *model in self.spotArray) {
            [array addObject:model.avatar];
        }
        self.images = array.copy;
        [self.currentCollection reloadData];
    }];
}

//上拉加载数据

- (void)loadTableViewDataSourceWithCityID:(NSString *)cityID start:(NSInteger)start limit:(NSInteger)limit{
    [RequestManager fetchDataWithUrl:@"http://www.roadqu.com/api/mobile/qunawan/poi/search" parameter:@{@"a_t":@"1468415212000",@"startpos":@"20",@"eachpage":@(limit),@"cityid":cityID,@"sign":@"0f4fee214ff654fa94b1c8b545538687440feaa8",@"a_t":@(1468415212000),@"token":@"578624ce19a3f"} method:@"POST" compeleted:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        for (NSDictionary *smallDic in dic[@"data"]) {
            SpotModel *desModol = [[SpotModel alloc]init];
            [desModol setValuesForKeysWithDictionary:smallDic];
            [self.spotArray addObject:desModol];
        }
    } updateUI:^{
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [self.tableView reloadData];
    }];
}


//导航栏点击事件
- (void)cityAction{
    if (!self.cityID) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"没有网络，请检查网络" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alert show];
    } else {
    
    if (self.city) {
        [self.visualImage removeFromSuperview];
        [self.visual removeFromSuperview];
        [self.city removeFromSuperview];
        self.tabBarController.tabBar.hidden = NO;
        self.city = nil;
        return;
    }
    self.city = [[CityView alloc] initWithFrame:CGRectMake(0, kHeight/3, kWidth, kHeight/2)];
    self.city.cityPick.delegate = self;
    self.city.cityPick.dataSource = self;
    [self.city.tureBtn addTarget:self action:@selector(tureAction) forControlEvents:UIControlEventTouchUpInside];
    [self.city.cancelBtn addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
    //选取出第一个滚轮中的值
    self.allCity = [self.specificDic.allKeys sortedArrayUsingSelector:@selector(compare:)];
    //根据第一个滚轮中的值，选取第二个滚轮中的值
    NSString *selectedState = [self.allCity objectAtIndex:0];
    NSArray *array = [self.specificDic objectForKey:selectedState];
    NSMutableArray *array1 = [NSMutableArray array];
    for (CityModel *city in array) {
        [array1 addObject:city.name];
    }
    self.seleCity = array1.copy;
    [self blurView];
    [self.view addSubview:self.city];
    self.tabBarController.tabBar.hidden = YES;
    }
}

//模糊试图
- (void)blurView{
    UIImageView *imageV = [[UIImageView alloc] initWithFrame:self.view.frame];
    imageV.image = [UIImage imageNamed:@"back.png"];
    UIVisualEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *visualView = [[UIVisualEffectView alloc] initWithEffect:effect];
    visualView.frame = CGRectMake(0, 64, kWidth, kHeight);
    visualView.alpha = 1;
    self.visualImage = imageV;
    self.visual = visualView;
    [self.view addSubview:self.visualImage];
    [self.view addSubview:self.visual];
}

- (void)tureAction{
    //获取选取器某一行索引值
    NSInteger spicificRow =[self.city.cityPick selectedRowInComponent:0];
    NSInteger cityRow = [self.city.cityPick selectedRowInComponent:1];
    //将singerData数组中值取出
    NSString *selectedSpicific = [self.allCity objectAtIndex:spicificRow];
    NSString *selectedCity = [self.seleCity objectAtIndex:cityRow];
    NSString *message = [[NSString alloc] initWithFormat:@"你选择了%@的%@",selectedSpicific,selectedCity];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
    
#warning 传值
    [PassValue sharePassValue].aString = selectedCity;
    
    
    
    
    
    //遍历需要搜索的所有内容，其中self.dataArray为存放总数据的数组
    for (NSString *string in self.specificDic) {
        NSArray *array = self.specificDic[string];
        for (CityModel *model in array) {
            NSString *tempStr = model.name;
            if ([selectedCity isEqualToString:tempStr]) {
                self.navigationItem.leftBarButtonItem.title = tempStr;
                [self requestSpotWithCityId:model.ID];
                self.cityID = model.ID.description;
            }
        }
    }

    
    [self.visualImage removeFromSuperview];
    [self.visual removeFromSuperview];
    [self.city removeFromSuperview];
    self.tabBarController.tabBar.hidden = NO;
    self.city = nil;
}

- (void)cancelAction{
    [self.visualImage removeFromSuperview];
    [self.visual removeFromSuperview];
    [self.city removeFromSuperview];
    self.tabBarController.tabBar.hidden = NO;
    self.city = nil;

}

//切换界面
- (void)loginAction{
    if (self.selectTrue == 1) {
        self.selectTrue = 0;
        [self.tableView reloadData];
        self.tabBarController.tabBar.hidden = YES;
        [self.view addSubview:self.tableView];
    } else {
        [self.tableView removeFromSuperview];
        self.tabBarController.tabBar.hidden = NO;

        self.selectTrue = 1;
    }
}


#pragma mark --pickViewDataSource

//返回显示的列数
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    //返回几就有几个选取器
    return 2;
}

//返回当前列显示的行数
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    
    if (component == 0) {
        return [self.allCity count];
    }
    return [self.seleCity count];
}

//返回当前行的内容,此处是将数组中数值添加到滚动的那个显示栏上
-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component==0) {
        return [self.allCity objectAtIndex:row];
    }
    
    return [self.seleCity objectAtIndex:row];
    
    
}
-(void)pickerView:(UIPickerView *)pickerViewt didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    // 如果选取的是第一个选取器
    if (component == 0) {
        // 得到第一个选取器的当前行
        NSString *selectedState =[self.allCity objectAtIndex:row];
        
        //根据从pickerDictionary字典中取出的值，选择对应第二个中的值
        NSArray *array = [self.specificDic objectForKey:selectedState];
        NSMutableArray *array1 = [NSMutableArray array];
        for (CityModel *city in array) {
            [array1 addObject:city.name];
        }
        self.seleCity = array1.copy;
        [self.city.cityPick selectRow:0 inComponent:1 animated:YES];
        //重新装载第二个滚轮中的值
        [self.city.cityPick reloadComponent:1];
    }
}
-(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    if (component == 0) {
        return 120;
    }
    return 200;
}

#pragma mark --CollectionDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.images.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
        ImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    if (self.cityID) {
        SpotModel *model = self.spotArray[indexPath.row];
        cell.labelText .text = model.name;
    }
        cell.backgroundColor = [UIColor whiteColor];
        cell.imageName = self.images[indexPath.row];
        cell.layer.cornerRadius = 40;
        cell.layer.masksToBounds = YES;
        return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (!self.cityID) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"没有网络，请检查网络" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alert show];
    } else {
    ShoppingViewController *play = [[ShoppingViewController alloc] init];
    SpotModel *model = self.spotArray[indexPath.row];
    play.VCid =  model.code;
        [self.navigationController pushViewController:play animated:YES];
    }
}

- (NSArray *)images {
    if (!_images) {
        _images = [NSArray array];
        _images = @[@"http://www.roadqu.com/data/attachment/poi/953e06f86165b0ea4153d30a1396b2c3_sc.jpg",@"http://www.roadqu.com/data/attachment/poi/953e06f86165b0ea4153d30a1396b2c3_sc.jpg",@"http://www.roadqu.com/data/attachment/poi/953e06f86165b0ea4153d30a1396b2c3_sc.jpg",@"http://www.roadqu.com/data/attachment/poi/953e06f86165b0ea4153d30a1396b2c3_sc.jpg",@"http://www.roadqu.com/data/attachment/poi/953e06f86165b0ea4153d30a1396b2c3_sc.jpg",@"http://www.roadqu.com/data/attachment/poi/953e06f86165b0ea4153d30a1396b2c3_sc.jpg",@"http://www.roadqu.com/data/attachment/poi/953e06f86165b0ea4153d30a1396b2c3_sc.jpg",@"http://www.roadqu.com/data/attachment/poi/953e06f86165b0ea4153d30a1396b2c3_sc.jpg",@"http://www.roadqu.com/data/attachment/poi/953e06f86165b0ea4153d30a1396b2c3_sc.jpg"];
       
    }
    return _images;
}

#pragma mark --UISearchDelegate
//在搜索框中修改搜索内容时，自动触发下面的方法
-(BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
    return YES;
}
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    [self.tableView removeFromSuperview];
    self.selectTrue = 1;
    [self.tableView reloadData];
//    NSLog(@"开始输入搜索内容");
    self.tabBarController.tabBar.hidden = YES;
    [self.view addSubview:self.tableView];
    searchBar.showsCancelButton = YES;//取消的字体颜色，
    [searchBar setShowsCancelButton:YES animated:YES];
    
    //改变取消的文本
    for(UIView *view in [[[searchBar subviews] objectAtIndex:0] subviews]) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *cancel =(UIButton *)view;
            [cancel setTitle:@"取消" forState:UIControlStateNormal];
            [cancel setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }
    }
}

-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    NSLog(@"输入搜索内容完毕");
}
//取消的响应事件
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    
    NSLog(@"取消搜索");
    [self.tableView removeFromSuperview];
    self.tabBarController.tabBar.hidden = NO;
    [searchBar setShowsCancelButton:NO animated:YES];
    [searchBar resignFirstResponder];
}

//搜框中输入关键字的事件响应
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    //需要事先情况存放搜索结果的数组
    [self.resultArray removeAllObjects];
    
    //加个多线程，否则数量量大的时候，有明显的卡顿现象
    //这里最好放在数据库里面再进行搜索，效率会更快一些
    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
    dispatch_async(globalQueue, ^{
        if (searchText!=nil && searchText.length>0) {
            
            //遍历需要搜索的所有内容，其中self.dataArray为存放总数据的数组
            for (NSString *string in self.specificDic) {
                NSArray *array = self.specificDic[string];
                for (CityModel *model in array) {
                    NSString *tempStr = model.name;
                //----------->把所有的搜索结果转成成拼音
                    NSString *pinyin = [self transformToPinyin:tempStr];
                    if ([pinyin rangeOfString:searchText options:NSCaseInsensitiveSearch].length >0 ) {
                        //把搜索结果存放self.resultArray数组
                        [self.resultArray addObject:model];
                    }
                }
            }
        }else {
            for (NSString *string in self.specificDic) {
                NSArray *array = self.specificDic[string];
                for (CityModel *model in array) {
                    [self.resultArray addObject:model];
                }
            }
        }
        //回到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    });
}
//!!!获取汉字转成拼音字符串 通讯录模糊搜索 支持拼音检索 首字母 全拼 汉字 搜索
- (NSString *)transformToPinyin:(NSString *)aString
{
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:aString];
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    NSArray *pinyinArray = [str componentsSeparatedByString:@" "];
    NSMutableString *allString = [NSMutableString new];
    
    int count = 0;
    
    for (int  i = 0; i < pinyinArray.count; i++)
    {
        
        for(int i = 0; i < pinyinArray.count;i++)
        {
            if (i == count) {
                [allString appendString:@"#"];//区分第几个字母
            }
            [allString appendFormat:@"%@",pinyinArray[i]];
            
        }
        [allString appendString:@","];
        count ++;
        
    }
    
    NSMutableString *initialStr = [NSMutableString new];//拼音首字母
    
    for (NSString *s in pinyinArray)
    {
        if (s.length > 0)
        {
            
            [initialStr appendString:  [s substringToIndex:1]];
        }
    }
    
    return allString;
}


//键盘上搜索事件的响应
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
    NSLog(@"搜索");
    [searchBar setShowsCancelButton:NO animated:YES];
    [searchBar resignFirstResponder];
}
#pragma mark --tableViewDatasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.selectTrue == 0) {
        return self.spotArray.count;
    } else {
    return self.resultArray.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.selectTrue == 0) {
        HomePageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"table_cell" forIndexPath:indexPath];
        SpotModel *model = self.spotArray[indexPath.row];
        [cell setCellWithModel:model];
        return cell;
    } else{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        cell.textLabel.text = [self.resultArray[indexPath.row] name];
        return cell;
    }
}

//tableView展示搜索内容
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.selectTrue == 0) {
        
        ShoppingViewController *play = [[ShoppingViewController alloc] init];
        SpotModel *model = self.spotArray[indexPath.row];
        play.VCid =  model.code;
        [self.navigationController pushViewController:play animated:YES];
        
    } else {
        CityModel *model = self.resultArray[indexPath.row];
        self.location.text = model.name;
        
        self.navigationItem.leftBarButtonItem.title = self.location.text;
        self.cityID = model.ID.description;
        [self requestSpotWithCityId:model.ID];
        [self.tableView removeFromSuperview];
        self.tabBarController.tabBar.hidden = NO;

    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.selectTrue == 0) {
        return 100;
    }
    return 50;
}


#pragma mark 地图的代理方法

- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location
{
//    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    [self.locationManager stopUpdatingLocation];
    //地理编码 反地理编码
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //将经纬度转换为地理信息
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *mark = placemarks.firstObject;
        NSLog(@"%@",mark.name);
        //遍历需要搜索的所有内容，其中self.dataArray为存放总数据的数组
        for (NSString *string in self.specificDic) {
            NSArray *array = self.specificDic[string];
            for (CityModel *model in array) {
                NSString *tempStr = model.name;
                if ([mark.name containsString:tempStr]) {
                    self.navigationItem.leftBarButtonItem.title = tempStr;
                    self.cityID = model.ID.description;
                    [self requestSpotWithCityId:model.ID];
                }
            }
        }
        
    }];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
}

@end
